package com.kcyu.sfherp.filter;

import com.kcyu.sfherp.entity.LoginUser;
import com.kcyu.sfherp.utils.JwtUtil;
import com.kcyu.sfherp.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    private String[] whiteList = {"swagger-ui", "swagger-resource", "favicon.ico", "api-docs"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        System.out.println("打印请求路径：" + request.getRequestURI());

        // 如果URL涉及白名单的话，直接放行
        for (String s : whiteList) {
            if(request.getRequestURI().contains(s)){
                filterChain.doFilter(request, response);
                return;
            }
        }

        if(request.getRequestURI().contains("/api/sys/") || request.getRequestURI().contains("/api/open/")){
            filterChain.doFilter(request, response);
            return;
        }

        // 在Cookies中获取token
        Cookie[] cookies = request.getCookies();
        String token = null;
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if("sfh-erp-token".equals(cookie.getName())){
                token = cookie.getValue();
            }
        }

//        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            // 放行
            filterChain.doFilter(request, response);
            return;
        }


        // 解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // 从redis中获取用户信息
        String redisKey = "login:" + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        // 存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);
    }
}
